package com.gitee.service.impl;

import com.gitee.constant.MessageConstant;
import com.gitee.context.BaseContext;
import com.gitee.dto.FriendUpdatesDTO;
import com.gitee.dto.FriendUpdatesStatesDTO;
import com.gitee.dto.PageQueryDTO;
import com.gitee.entity.FriendUpdates;
import com.gitee.entity.FriendUpdatesStates;
import com.gitee.exception.CollectionException;
import com.gitee.mapper.FollowListMapper;
import com.gitee.mapper.FriendUpdatesMapper;
import com.gitee.mapper.FriendUpdatesStatesMapper;
import com.gitee.mapper.CommentMapper;
import com.gitee.service.FriendUpdatesService;
import com.gitee.vo.FriendUpdatesVO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.LinkedList;
import java.util.List;

@Service
public class FriendUpdatesServiceImpl implements FriendUpdatesService {

    @Resource
    private FriendUpdatesMapper friendUpdatesMapper;
    @Resource
    private FollowListMapper followListMapper;
    @Resource
    private FriendUpdatesStatesMapper friendUpdatesStatesMapper;
    @Resource
    private CommentMapper commentMapper;

    @Override
    public List<FriendUpdatesVO> pageQuery(PageQueryDTO pageQueryDTO) {
        // select * from sxq_friend_updates limit n m
        // n = (n - 1) * m
        int m = pageQueryDTO.getPageSize();
        int n = (pageQueryDTO.getCurrentPage() - 1) * m;
        // 只展示好友和自己的
        // select * from sxq_friend_updates where user_id in(#{list}) limit n m
        // 查找该用户关注的用户
        Integer currentId = BaseContext.getCurrentId();
        List<Integer> followUserId = new LinkedList<>();
        followListMapper.selectByUserId(currentId).forEach(it -> followUserId.add(it.getFollowId()));
        followUserId.add(currentId);
        return friendUpdatesMapper.pageQuery(n, m, followUserId);
    }

    @Override
    public void save(FriendUpdatesDTO friendUpdatesDTO) {
        FriendUpdates friendUpdates = new FriendUpdates();
        BeanUtils.copyProperties(friendUpdatesDTO, friendUpdates);
        friendUpdatesMapper.insert(friendUpdates);
    }

    @Override
    public Long count(Integer userId) {
        // 只展示好友和自己的
        // select * from sxq_friend_updates where user_id in(#{list}) limit n m
        // 查找该用户关注的用户
        List<Integer> followUserId = new LinkedList<>();
        followListMapper.selectByUserId(userId).forEach(it -> followUserId.add(it.getFollowId()));
        followUserId.add(userId);
        return friendUpdatesMapper.count(followUserId);
    }

    @Override
    @Transactional
    public void setState(FriendUpdatesStatesDTO friendUpdatesStatesDTO) {
        /*
         * 分析:
         *      查找该用户是否有修改记录
         *      select * from sxq_friend_updates_states where user_id = #{user_id} and friend_updates_id = #{friendUpdatesId}
         *
         *      如果当前登录用户对目标动态无修改记录, 则插入新纪录
         *      insert into sxq_friend_updates_states values(null, #{friendUpdatesId}, ...)
         *
         *      如果当前用户有对该表操作的记录, 则修改
         *      update sxq_friend_updates_states set hits_state = #{hitState} where friend_updates_id = #{friendUpdatesId}
         */
        Integer currentId = BaseContext.getCurrentId();
        FriendUpdatesStates friendUpdatesStates = friendUpdatesStatesMapper.selectByUserIdAndFriendUpdatesId(currentId, friendUpdatesStatesDTO.getFriendUpdatesId());
        // 为空则代表无修改记录
        if (friendUpdatesStates == null) {
            // 插入新数据
            friendUpdatesStates = new FriendUpdatesStates();
            BeanUtils.copyProperties(friendUpdatesStatesDTO, friendUpdatesStates);
            friendUpdatesStates.setUserId(currentId);
            friendUpdatesStatesMapper.insert(friendUpdatesStates);
        } else {
            // 判断要修改的项
            if (friendUpdatesStatesDTO.getHitsState() != null && friendUpdatesStatesDTO.getHitsState()) {
                // 观看量只能增不能减
                friendUpdatesStates.setHitsState(true);

            } else if (friendUpdatesStatesDTO.getCollectState() != null && friendUpdatesStatesDTO.getCollectState()) {
                // 若要修改的项已被修改, 则false, 否则为true
                friendUpdatesStates.setCollectState(!(friendUpdatesStates.getCollectState() != null && friendUpdatesStates.getCollectState()));

            } else if (friendUpdatesStatesDTO.getLikeState() != null && friendUpdatesStatesDTO.getLikeState()) {
                friendUpdatesStates.setLikeState(!(friendUpdatesStates.getLikeState() != null && friendUpdatesStates.getLikeState()));
            }
            friendUpdatesStatesMapper.updateByFriendUpdatesIdAndUserId(friendUpdatesStates);
        }

        // 通过动态id锁定某个动态
        // 更新改文章的所有阅读数, 点赞数, 收藏数
        // 首先统计三者的数量
        FriendUpdates friendUpdates = new FriendUpdates();
        friendUpdates.setHitsCount(friendUpdatesStatesMapper.countHits(friendUpdatesStates.getFriendUpdatesId()));
        friendUpdates.setLikeCount(friendUpdatesStatesMapper.countLike(friendUpdatesStates.getFriendUpdatesId()));
        friendUpdates.setCollectCount(friendUpdatesStatesMapper.countCollect(friendUpdatesStates.getFriendUpdatesId()));
        friendUpdates.setId(friendUpdatesStates.getFriendUpdatesId());
        friendUpdatesMapper.updateById(friendUpdates);
    }

    @Override
    public List<FriendUpdatesVO> getFriendUpdatesVOByTitle(String title) {
        return friendUpdatesMapper.selectByTitle("*".equals(title) ? null : title);
    }

    @Override
    public FriendUpdatesVO getFriendUpdateById(Integer id) {
        return friendUpdatesMapper.selectById(id);
    }

    @Override
    public List<FriendUpdatesVO> getFriendUpdateByUserId(Integer userId) {
        return friendUpdatesMapper.selectByUserId(userId);
    }

    @Override
    public List<FriendUpdatesVO> getCollectionFriendUpdate(Integer userId) {
        // 首先查找该用户所有的收藏
        List<Integer> friendUpdatesIds = friendUpdatesStatesMapper.selectCollectionByUserId(userId);
        if (friendUpdatesIds == null || friendUpdatesIds.isEmpty()) {
            throw new CollectionException(MessageConstant.NOT_COLLECTION);
        }
        List<FriendUpdatesVO> friendUpdatesVOS = friendUpdatesMapper.selectByIds(friendUpdatesIds);
        if (friendUpdatesVOS == null) {
            throw new CollectionException(MessageConstant.NOT_COLLECTION);
        }
        return friendUpdatesVOS;
    }

    @Override
    public Long getUserLikeCount(Integer userId) {
        List<Long> longs = friendUpdatesMapper.countUserLike(userId);
        long sum = 0;
        if (longs == null || longs.isEmpty()) {
            return 0L;
        }

        for (Long aLong : longs) {
            if (aLong != null) {
                sum += aLong;
            }
        }
        return sum;
    }

    @Override
    public void deleteFriendUpdate(Integer friendUpdateId) {
        // 删除评论
        commentMapper.deleteByFriendUpdatesId(friendUpdateId);
        // 删除点赞
        friendUpdatesStatesMapper.deleteByFriendUpdatesId(friendUpdateId);
        // 删除动态
        friendUpdatesMapper.deleteById(friendUpdateId);
    }
}
